package com.demo2.todo.service.impl;

import com.demo2.todo.model.entity.Todo;
import com.demo2.todo.model.entity.User;
import com.demo2.todo.model.enums.TodoStatus;
import com.demo2.todo.repository.TodoRepository;
import com.demo2.todo.service.ReminderService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author evi
 */
@Service
@RequiredArgsConstructor
public class ReminderServiceImpl implements ReminderService {

    private final TodoRepository todoRepository;

    // 每天上午9点执行
    @Scheduled(cron = "0 0 9 * * ?")
    @Override
    @Transactional
    public void sendDeadlineReminders() {
        // 查询24小时内即将到期且未完成的任务
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime tomorrow = now.plusDays(1);

        List<Todo> upcomingTodos = todoRepository.findByStatusAndDeadlineBetween(
                TodoStatus.pending, now, tomorrow
        );

        // 发送提醒
        for (Todo todo : upcomingTodos) {
            User user = todo.getUser();
            if (user.isEnabled()) {
                String subject = "任务到期提醒: " + todo.getTitle();
                String content = String.format(
                        "您的任务「%s」将在24小时内到期，请及时处理。\n\n任务内容: %s\n到期时间: %s",
                        todo.getTitle(),
                        todo.getContent(),
                        todo.getDeadline()
                );
            }
        }
    }
}
